package com.lw.leetcode.bit.b;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/8 9:05
 */
public class FindRepeatedDnaSequences {

    public static void main(String[] args) {
        FindRepeatedDnaSequences test = new FindRepeatedDnaSequences();
        String str = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT";
        List<String> repeatedDnaSequences = test.findRepeatedDnaSequences(str);
        System.out.println(repeatedDnaSequences);

        int i = scale2Decimal("11000000000000000000", 2);
        System.out.println(i);
    }

    public List<String> findRepeatedDnaSequences(String s) {

        int length = s.length();
        if (length < 11) {
            return Collections.emptyList();
        }
        Map<Integer, Integer> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        Map<Character, Integer> c = new HashMap<>();
        c.put('A', 0);
        c.put('C', 1);
        c.put('G', 2);
        c.put('T', 3);
        int item = 0;
        for (int i = 0; i < 10; i++) {
            item |= (c.get(s.charAt(i)) << ((9 - i) << 1));
        }
        map.put(item, 1);
        StringBuilder sb = new StringBuilder(10);
        for (int i = 10; i < length; i++) {
            item <<= 2;
            item |= c.get(s.charAt(i));
            item &= 1048575;
            Integer value = map.get(item);
            if (value == null) {
                map.put(item, 1);
            } else if (value == 1) {
                map.put(item, 2);
                int n = item;
                for (int j = 0; j < 10; j++) {
                    int index = (n & 786432) >> 18;
                    switch (index) {
                        case 0:
                            sb.append('A');
                            break;
                        case 1:
                            sb.append('C');
                            break;
                        case 2:
                            sb.append('G');
                            break;
                        default:
                            sb.append('T');
                            break;
                    }
                    n <<= 2;
                }
                list.add(sb.toString());
                sb.setLength(0);
            }
        }
        return list;
    }

    /**
     * 其他进制转十进制
     * @param number
     * @return
     */
    public static int scale2Decimal(String number, int scale) {
        if (2 > scale || scale > 32) {
            throw new IllegalArgumentException("scale is not in range");
        }
        // 不同其他进制转十进制,修改这里即可
        int total = 0;
        String[] ch = number.split("");
        int chLength = ch.length;
        for (int i = 0; i < chLength; i++) {
            total += Integer.valueOf(ch[i]) * Math.pow(scale, chLength - 1 - i);
        }
        return total;

    }

}
